import { download, initData, initDataPlus } from '@/api/data'
import { dictName, dictNameArray, downloadFile, getNowTime, parseData, parseDate, parseTime } from '@/utils/index'
import Vue from 'vue'
import crudHeaderProperties from '@/api/erp/headerProperties'
import { Loading } from 'element-ui'
import { ignorePromotionPass } from '../../api/erp/salesOrder'

/**
 * CRUD配置
 * @author moxun
 * @param {*} options <br>
 * @param page
 * @return crud instance.
 * @example
 */
function CRUD(options) {
  const page = options.page || { page: 1, size: 20, total: 0 }
  const defaultOptions = {
    // 标题
    title: '',
    // 请求数据的url
    url: '',
    // 请求头
    header: [],
    headerInfo: null,
    daysOfMonth: null,
    // 表头请求属性
    name: '',
    // 表格数据
    data: [],
    // 合计数据
    summary: [],
    // 单据详情表单
    order: {},
    // 选择项
    selections: [],
    // 待查询的对象
    query: {},
    // 查询数据的参数
    params: {},
    // Form 表单
    form: {},
    // 重置表单
    defaultForm: () => {
    },
    // 排序规则，默认 id 降序， 支持多字段排序 ['id,desc', 'createTime,asc']
    sort: ['id,desc'],
    // 等待时间
    time: 50,
    // CRUD Method
    crudMethod: {
      add: (form) => {
      },
      delete: (id) => {
      },
      edit: (form) => {
      },
      get: (id) => {
      },
      enableOrDisable: (obj) => {
      },
      passOrReject: (obj) => { }
    },
    // 主页操作栏显示哪些按钮
    optShow: {
      isShow: true,
      add: true,
      edit: true,
      del: true,
      download: true,
      leadingIn: true,
      enable: true,
      disable: true,
      pass: false,
      reject: false,
      copy: false,
      downloadDetail: false,
      recover: false,
      invalid: false,
      print: false, // 打印
      printDetail: false, // 打印详情
      unAccept: false, // 反验收
      accept: false // 验收
    },
    // 自定义一些扩展属性
    props: {},
    // 在主页准备
    queryOnPresenterCreated: true,
    // 调试开关
    debug: false,
    // 整体loading
    loading: true,
    // 导出的 Loading
    downloadLoading: false,
    // 导详情的 Loading
    downloadDetailLoading: false,
    // 打印的 Loading
    printLoading: false,
    // 删除的 Loading
    delAllLoading: false,
    // 反审的 Loading
    rejectLoading: false,
    // 审核的 Loading
    passLoading: false,
    // 作废的 Loading
    invalidLoading: false,
    // 恢复的 Loading
    recoverLoading: false,
    // 启用的 Loading
    enableLoading: false,
    // 禁用的 Loading
    disableLoading: false,
    // 中止的 Loading
    stopLoading: false,
    // 消息框
    isShowMsg: false,
    // 复制 Loading
    copyLoading: false,
    // 验收 Loading
    acceptLoading: false,
    // 复制为退货
    copyToReturnLoading: false,
    // 解锁
    lockStockLoading: false,
    // 打印
    printConfig: {
      // 是否预览
      isPreview: 0,
      pringDialog: false
    },
    selectedIndex: [],
    //默认请求类型
    queryType:'get'
  }
  options = mergeOptions(defaultOptions, options)
  const data = {
    ...options,
    // 记录数据状态
    dataStatus: {},
    status: {
      add: CRUD.STATUS.NORMAL,
      edit: CRUD.STATUS.NORMAL,
      // 添加或编辑状态
      get cu() {
        if (this.add === CRUD.STATUS.NORMAL && this.edit === CRUD.STATUS.NORMAL) {
          return CRUD.STATUS.NORMAL
        } else if (this.add === CRUD.STATUS.PREPARED || this.edit === CRUD.STATUS.PREPARED) {
          return CRUD.STATUS.PREPARED
        } else if (this.add === CRUD.STATUS.PROCESSING || this.edit === CRUD.STATUS.PROCESSING) {
          return CRUD.STATUS.PROCESSING
        }
        throw new Error('wrong crud\'s cu status')
      },
      // 标题
      get title() {
        return this.add > CRUD.STATUS.NORMAL ? `新增${crud.title}` : this.edit > CRUD.STATUS.NORMAL ? `编辑${crud.title}` : crud.title
      }
    },
    msg: {
      submit: '提交成功',
      add: '新增成功',
      edit: '编辑成功',
      del: '删除成功'
    },
    page,
    saveFlag: false, // 新增缓存
    // 整体loading
    loading: true,
    // 导出的 Loading
    downloadLoading: false,
    // 删除的 Loading
    delAllLoading: false,
    // 启用禁用的loading
    enableOrDisableLoading: false
  }
  const methods = {
    /**
         * 通用的提示
         */
    submitSuccessNotify() {
      crud.notify(crud.msg.submit, CRUD.NOTIFICATION_TYPE.SUCCESS)
    },
    addSuccessNotify() {
      crud.notify(crud.msg.add, CRUD.NOTIFICATION_TYPE.SUCCESS)
    },
    editSuccessNotify() {
      crud.notify(crud.msg.edit, CRUD.NOTIFICATION_TYPE.SUCCESS)
    },
    delSuccessNotify() {
      crud.notify(crud.msg.del, CRUD.NOTIFICATION_TYPE.SUCCESS)
    },
    // 新增缓存
    setItemInfo(name) {
      if (crud.saveFlag) {
        crud.saveFlag = false
        crud.order.detailList = crud.data
        localStorage.setItem(name, JSON.stringify(crud.order))
      }
    },
    // 清除缓存
    cleanItemInfo(name) {
      crud.saveFlag = false
      crud.data = []
      localStorage.removeItem(name)
    },
    // 读取缓存
    getItemInfo(name) {
      crud.data = []
      crud.saveFlag = true
      const _form = JSON.parse(localStorage.getItem(name))
      if (_form) {
        crud.order = _form
        crud.data = _form.detailList
        return true
      } else {
        crud.data = []
        crud.refresh()
        return false
      }
    },
    // 搜索
    toQuery() {
      crud.page.page = 1
      crud.refresh()
    },
    // 刷新
    refresh() {
      if (!callVmHook(crud, CRUD.HOOK.beforeRefresh)) {
        return
      }
      return new Promise((resolve, reject) => {
        crud.loading = true
        // 请求数据
        if (crud.getQueryParams().id == 0) {
          crud.loading = false
          return false
        }
        initData(crud.url, crud.getQueryParams(),crud.queryType).then(res => {
          let data = res
          if (res.data) {
            data = res.data
          }
          if (res.data && res.data.daysOfMonth) crud.daysOfMonth = res.data.daysOfMonth
          crud.page.total = data.totalElements
          crud.data = data.content||data
          crud.order = data.order || crud.order
          crud.summary = data.summary || data.reportCustomerReceiveSummary
          crud.resetDataStatus()
          // time 毫秒后显示表格
          setTimeout(() => {
            crud.loading = false
            callVmHook(crud, CRUD.HOOK.afterRefresh, data)
          }, crud.time)
          resolve(data)
          if (data.header) {

            crud.headerInfo = data.header
            crud.header = JSON.parse(data.header.content).filter(item => item)

          }
        }).catch(err => {
          crud.loading = false
          reject(err)
        })
      })
    },

    /**
     * 表头自适应
     */
    renderHeader(h, { column, $index }) {
      const span = document.createElement('span')
      span.innerText = column.label
      document.body.appendChild(span)
      if (column.label) column.minWidth = column.label.length * 20 + 25
      if (column.label === '客户' || column.label === '备注') {
        column.minWidth = 200
      }
      document.body.removeChild(span)
      return h('span', column.label)
    },
    /**
     * 选中行
     */
    selectRow(row, column, event) {
      crud.findVM('presenter').$refs['table'].toggleRowSelection(row)
    },
    /**
     * 打印
     */
    preView() {
      crud.printConfig.isPreview = 0
      crud.printConfig.pringDialog = true
    },
    preView1() {
      crud.printConfig.isPreview = 1
      crud.printConfig.pringDialog = true
    },
    toPrint(val) {
      if (val !== null) {
        crud.printConfig.pringDialog = false
        crud.doPrint(val, [], crud.printConfig.isPreview)
      } else {
        this.$message.error('请选择打印模板')
      }
    },
    detailedPrint(val) {
      if (val !== null) {
        crud.printConfig.pringDialog = false
        const urlList = window.location.href.split('/')
        const id = urlList[urlList.length - 1].split('?')[0]
        crud.doPrint(val, [id], crud.printConfig.isPreview)
      } else {
        this.$message.error('请选择打印模板')
      }
    },

    /**
     * 通用打印
     */
    doPrint(templateId, rowIds, isPreview, ev) {
      let ids
      if (rowIds.length === 0) {
        ids = crud.selections.map(item => item.id)
      } else {
        ids = rowIds
      }
      let data = { ids, templateId, isPreview }
      if (ev === 'salesOrderPrint') {
        data = { orderId: crud.order.id, salesOrderIds: ids, templateId, isPreview }
      } if (ev === 'logisticsLoadGoodsPrint') {
        data = { orderId: crud.order.id, templateId, isPreview }
      }
      crud.printLoading = true
      const method = `crud.crudMethod.${!ev ? 'print' : ev}`
      eval(`${method}(data)`).then(res => {

        const blob = new Blob([res], { type: 'application/pdf' })
        if (isPreview) {
          // 打印预览
          crud.findVM('presenter').pdfSrc = window.URL.createObjectURL(blob)
          crud.findVM('presenter').showPdf = true
          return
        }
        var date = (new Date()).getTime()
        var iframe = document.createElement('iframe')
        iframe.style.frameborder = 'no'
        iframe.style.display = 'none'
        iframe.style.pageBreakBefore = 'always'
        iframe.setAttribute('id', 'printPdf' + date)
        iframe.setAttribute('name', 'printPdf' + date)
        iframe.src = window.URL.createObjectURL(blob)
        document.body.appendChild(iframe)
        var printWindow = document.getElementById('printPdf' + date).contentWindow
        setTimeout(() => {
          printWindow.print()
          crud.printLoading = false
        }, 100)
        window.URL.revokeObjectURL(iframe.src)
        crud.printLoading = false
      }).catch(e => {
        crud.printLoading = false
      })
    },
    /**
     * 配送单销售单打印特殊处理
     */
    salesOrderPrintHandler(templateId, rowIds, seqList, isPreview, ev) {
      let ids
      if (rowIds.length === 0) {
        ids = crud.selections.map(item => item.id)
      } else {
        ids = rowIds
      }
      const data = { orderId: crud.order.id, salesOrderIds: ids, salesOrderSeqList: seqList, templateId, isPreview }
      crud.printLoading = true
      const method = `crud.crudMethod.${!ev ? 'print' : ev}`
      eval(`${method}(data)`).then(res => {
        const blob = new Blob([res], { type: 'application/pdf' })
        if (isPreview) {
          // 打印预览
          crud.findVM('presenter').pdfSrc = window.URL.createObjectURL(blob)
          crud.findVM('presenter').showPdf = true
          return
        }
        var date = (new Date()).getTime()
        var iframe = document.createElement('iframe')
        iframe.style.frameborder = 'no'
        iframe.style.display = 'none'
        iframe.style.pageBreakBefore = 'always'
        iframe.setAttribute('id', 'printPdf' + date)
        iframe.setAttribute('name', 'printPdf' + date)
        iframe.src = window.URL.createObjectURL(blob)
        document.body.appendChild(iframe)
        var printWindow = document.getElementById('printPdf' + date).contentWindow
        setTimeout(() => {
          printWindow.print()
          crud.printLoading = false
        }, 100)
        window.URL.revokeObjectURL(iframe.src)
        crud.printLoading = false
      }).catch(e => {
        crud.printLoading = false
      })
    },
    /**
     * 执行详情审核/反审/作废/恢复
     */
    doDetailPassOrReject(type, form) {
      this.doLoading(type, true)
      const params = crud.findVM('presenter').$route.params
      const id = params.id || form.id
      crud.loadingOpen()
      crud.crudMethod.passOrReject({ ids: [parseInt(id)], type }).then(res => {
        crud.loadingClose()
        if (res.success) {
          crud.notify(res.msg, CRUD.NOTIFICATION_TYPE.SUCCESS)
          crud.refresh()
          if (crud.order.id) {
            if (type === 'REJECT') {
              crud.order.orderStatus = 'SAVE'
            } else {
              crud.order.orderStatus = type
            }
          } else {
            if (type === 'REJECT') {
              form.orderStatus = 'SAVE'
            } else {
              form.orderStatus = type
            }
          }
        } else {
          crud.notify(res.msg, CRUD.NOTIFICATION_TYPE.ERROR)
          crud.refresh()
        }
        this.doLoading(type, false)
      }).catch(e => {
        crud.loadingClose()
        crud.refresh()
        this.doLoading(type, false)
      })
    },
    /**
         * 启动添加
         */
    toAdd() {
      crud.form.EDITTYPE = 'ADD'
      if (!(callVmHook(crud, CRUD.HOOK.beforeToAdd, crud.form) && callVmHook(crud, CRUD.HOOK.beforeToCU, crud.form))) {
        return
      }
      crud.status.add = CRUD.STATUS.PREPARED
      callVmHook(crud, CRUD.HOOK.afterToAdd, crud.form)
      callVmHook(crud, CRUD.HOOK.afterToCU, crud.form)
    },
    /**
         * 启动编辑
         * @param {*} data 数据项a
         */
    toEdit(data) {
      crud.form.DISABLED = data.status === 0
      crud.form.businessAttr = data.businessAttr
      crud.resetForm(JSON.parse(JSON.stringify(data)))
      if (!(callVmHook(crud, CRUD.HOOK.beforeToEdit, crud.form) && callVmHook(crud, CRUD.HOOK.beforeToCU, crud.form))) {
        return
      }
      crud.status.edit = CRUD.STATUS.PREPARED
      crud.getDataStatus(data.id).edit = CRUD.STATUS.PREPARED
      callVmHook(crud, CRUD.HOOK.afterToEdit, crud.form)
      callVmHook(crud, CRUD.HOOK.afterToCU, crud.form)
    },
    /**
         * 启动删除
         * @param {*} data 数据项
         */
    toDelete(data) {
      crud.getDataStatus(data.id).delete = CRUD.STATUS.PREPARED
    },
    /**
         * 取消删除
         * @param {*} data 数据项
         */
    cancelDelete(data) {
      if (!callVmHook(crud, CRUD.HOOK.beforeDeleteCancel, data)) {
        return
      }
      crud.getDataStatus(data.id).delete = CRUD.STATUS.NORMAL
      callVmHook(crud, CRUD.HOOK.afterDeleteCancel, data)
    },
    /**
         * 取消新增/编辑
         */
    cancelCU() {
      const addStatus = crud.status.add
      const editStatus = crud.status.edit
      if (addStatus === CRUD.STATUS.PREPARED) {
        if (!callVmHook(crud, CRUD.HOOK.beforeAddCancel, crud.form)) {
          return
        }
        crud.status.add = CRUD.STATUS.NORMAL
      }
      if (editStatus === CRUD.STATUS.PREPARED) {
        if (!callVmHook(crud, CRUD.HOOK.beforeEditCancel, crud.form)) {
          return
        }
        crud.status.edit = CRUD.STATUS.NORMAL
        crud.getDataStatus(crud.form.id).edit = CRUD.STATUS.NORMAL
      }
      crud.resetForm()
      if (addStatus === CRUD.STATUS.PREPARED) {
        callVmHook(crud, CRUD.HOOK.afterAddCancel, crud.form)
      }
      if (editStatus === CRUD.STATUS.PREPARED) {
        callVmHook(crud, CRUD.HOOK.afterEditCancel, crud.form)
      }
      // 清除表单验证
      if (crud.findVM('form').$refs['form']) {
        crud.findVM('form').$refs['form'].clearValidate()
      }
    },
    /**
         * 提交新增/编辑
         */
    submitCU() {
      if (!callVmHook(crud, CRUD.HOOK.beforeValidateCU)) {
        return
      }

      crud.findVM('form').$refs['form'].validate(valid => {
        if (!valid) {
          return
        }
        if (!callVmHook(crud, CRUD.HOOK.afterValidateCU)) {
          return
        }
        if (crud.status.add === CRUD.STATUS.PREPARED) {
          crud.doAdd()
        } else if (crud.status.edit === CRUD.STATUS.PREPARED) {
          crud.doEdit()
        } else {
          crud.doAdd()
        }
      })
    },
    /**
         * 执行添加
         */
    doAdd() {
      if (!callVmHook(crud, CRUD.HOOK.beforeSubmit)) {
        return
      }
      crud.loadingOpen()
      crud.crudMethod.add(crud.form).then(() => {
        crud.status.add = CRUD.STATUS.NORMAL
        crud.resetForm()
        crud.addSuccessNotify()
        callVmHook(crud, CRUD.HOOK.afterSubmit)
        crud.loadingClose()
        crud.toQuery()
      }).catch(() => {
        crud.loadingClose()
        callVmHook(crud, CRUD.HOOK.afterAddError)
      })
    },
    /**
         * 执行编辑
         */
    doEdit() {
      if (!callVmHook(crud, CRUD.HOOK.beforeSubmit)) {
        return
      }
      crud.crudMethod.edit(crud.form).then(() => {
        crud.status.edit = CRUD.STATUS.NORMAL
        crud.getDataStatus(crud.form.id).edit = CRUD.STATUS.NORMAL
        crud.editSuccessNotify()
        crud.resetForm()
        callVmHook(crud, CRUD.HOOK.afterSubmit)
        crud.refresh()
      }).catch(() => {
        callVmHook(crud, CRUD.HOOK.afterEditError)
      })
    },
    /**
         * 修改项目状态
         * @param type 类型，一般内容如下:
         * 审核PASS 反审REJECT 关闭CLOSED 作废INVALID 中止STOP 恢复RECOVER 启用ENABLE 禁用DISABLE
         */
    enableOrDisable(type, id) {
      crud.loadingOpen()
      const ids = []
      if (id) {
        const href = location.href.split('/')
        if (href[5].includes('copyId')) {
          const strs = id.split('=')
          ids.push(strs[1])
        } else {
          ids.push(id)
        }
      } else {
        const _datas = crud.selections
        // 获取选中的内容
        _datas.forEach(o => {
          ids.push(o.id)
        })
      }
      crud.crudMethod.enableOrDisable({ ids: ids, type: type }).then(() => {
        crud.loadingClose()
        crud.resetForm()
        Vue.prototype.$message.success('操作成功')
        callVmHook(crud, CRUD.HOOK.afterSubmit)
        crud.refresh()
      }).catch(() => {
        crud.loadingClose()
        callVmHook(crud, CRUD.HOOK.afterEditError)
        Vue.prototype.$message.error('修改失败，稍后再试')
      })
    },
    passOrReject(type) {
      crud.enableOrDisableLoading = true
      const ids = []
      const _datas = crud.selections
      // 获取选中的内容
      _datas.forEach(o => {
        ids.push(o.id)
      })
      crud.crudMethod.passOrReject({ ids: ids, type: type }).then(() => {
        crud.enableOrDisableLoading = false
        crud.resetForm()
        Vue.prototype.$message.success('修改成功')
        callVmHook(crud, CRUD.HOOK.afterSubmit)
        crud.refresh()
      }).catch(() => {
        crud.enableOrDisableLoading = false
        callVmHook(crud, CRUD.HOOK.afterEditError)
        Vue.prototype.$message.error('修改失败，稍后再试')
      })
    },
    /**
     * 跳转到详情界面
     */
    toDetail(url, row) {
      const ids = row === undefined ? 'add' : row
      crud.findVM('presenter').$router.push({ path: url + '/' + ids })
    },
    /**
     * 自适应屏幕
     * @returns {number}
     */
    getRatio() {
      var ratio = 0
      var screen = window.screen
      var ua = navigator.userAgent.toLowerCase()

      if (window.devicePixelRatio !== undefined) {
        ratio = window.devicePixelRatio
      } else if (~ua.indexOf('msie')) {
        if (screen.deviceXDPI && screen.logicalXDPI) {
          ratio = screen.deviceXDPI / screen.logicalXDPI
        }
      } else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
        ratio = window.outerWidth / window.innerWidth
      }

      if (ratio) {
        ratio = Math.round(ratio * 100)
      }
      return ratio
    },
    /**
         * 执行删除
         * @param {*} data 数据项
         */
    doDelete(data) {
      let delAll = false
      let dataStatus
      const ids = []
      if (data instanceof Array) {
        delAll = true
        data.forEach(val => {
          ids.push(val.id)
        })
      } else {
        ids.push(data.id)
        dataStatus = crud.getDataStatus(data.id)
      }
      if (!callVmHook(crud, CRUD.HOOK.beforeDelete, data)) {
        return
      }
      if (!delAll) {
        dataStatus.delete = CRUD.STATUS.PROCESSING
      }
      return crud.crudMethod.del(ids).then(() => {
        if (delAll) {
          crud.delAllLoading = false
        } else dataStatus.delete = CRUD.STATUS.PREPARED
        crud.dleChangePage(1)
        crud.delSuccessNotify()
        callVmHook(crud, CRUD.HOOK.afterDelete, data)
        crud.refresh()
      }).catch(() => {
        if (delAll) {
          crud.delAllLoading = false
        } else dataStatus.delete = CRUD.STATUS.PREPARED
        crud.refresh()
      })
    },
    /**
         * 通用导出
         */
    doExport() {
      crud.downloadLoading = true
      if (crud.selections.length > 0) {
        crud.query.ids = ''
        crud.selections.forEach(item => {
          crud.query.ids += item.id + ','
        })
      } else {
        crud.query.ids = ''
      }
      if (crud.url === '/api/basGoodsPriceSuit/detail') crud.url = '/api/basGoodsPriceSuitDetail'
      else if (crud.url === '/api/reportSalesmanTrace/queryAll') crud.url = '/api/reportSalesmanTrace'
      download(crud.url + '/export', crud.getQueryParams(),crud.queryType).then(result => {
        downloadFile(result, crud.title + '数据', 'xlsx')
        crud.downloadLoading = false
      }).catch(() => {
        crud.downloadLoading = false
      })
    },
    /**
         * 通用导入
         */
    doLeadingIn() {
      crud.downloadLoading = true
      // download(crud.url + '/import', crud.getQueryParams()).then(result => {
      //   downloadFile(result, crud.title + '数据', 'xlsx')
      //   crud.downloadLoading = false
      // }).catch(() => {
      //   crud.downloadLoading = false
      // })
    },
    loadingOpen() {
      Loading.service(crud.loadingOption)
    },
    loadingClose() {
      Vue.nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
        Loading.service(crud.loadingOption).close()
      })
    },
    /**
         * 获取查询参数
         */
    getQueryParams: function() {
      return {
        page: crud.page.page,
        size: crud.page.size,
        sort: crud.sort,
        ...crud.query,
        ...(typeof crud.params === 'function' ? crud.params() : crud.params)
      }
    },
    /**
     * 跳转到详情界面
     */
    toDetailPlus(url, row) {
      const ids = row === undefined ? 'add' : row
      crud.findVM('presenter').$router.push({ path: url + '/' + ids })
    },
    // 当前页改变
    pageChangeHandler(e) {
      crud.page.page = e
      crud.refresh()
    },
    // 每页条数改变
    sizeChangeHandler(e) {
      crud.page.size = e
      crud.page.page = 1
      crud.refresh()
    },
    // 预防删除第二页最后一条数据时，或者多选删除第二页的数据时，页码错误导致请求无数据
    dleChangePage(size) {
      if (crud.data.length === size && crud.page.page !== 1) {
        crud.page.page -= 1
      }
    },
    // 选择改变
    selectionChangeHandler(val) {
      crud.selections = val
      crud.selectedIndex = val.map(item => item.index)
    },
    rowClass({ row, rowIndex }) {
      if (crud.selectedIndex.indexOf(rowIndex) >= 0) {
        return {
          'border': 'solid 1px #3dffef',
          'background-color': '#fafc7e ',
          'height': '10px'
        }
      } else {
        return {
          'height': '10px'
        }
      }
    },
    /**
         * 重置查询参数
         * @param {Boolean} toQuery 重置后进行查询操作
         */
    resetQuery(toQuery = true) {
      const defaultQuery = JSON.parse(JSON.stringify(crud.defaultQuery))
      const query = crud.query
      Object.keys(query).forEach(key => {
        query[key] = defaultQuery[key]
      })
      if (toQuery) {
        crud.toQuery()
      }
    },
    doLoading(type, loading) {
      switch (type) {
        case 'PASS':
          crud.passLoading = loading
          break
        case 'REJECT':
          crud.rejectLoading = loading
          break
        case 'INVALID':
          crud.invalidLoading = loading
          break
        case 'RECOVER':
          crud.recoverLoading = loading
          break
        case 'STOP':
          crud.stopLoading = loading
          break
      }
    },
    /**
         * 重置表单
         * @param {Array} data 数据
         */
    resetForm(data) {
      const form = data || (typeof crud.defaultForm === 'object' ? JSON.parse(JSON.stringify(crud.defaultForm)) : crud.defaultForm())
      const crudFrom = crud.form
      for (const key in form) {
        if (crudFrom.hasOwnProperty(key)) {
          crudFrom[key] = form[key]
        } else {
          Vue.set(crudFrom, key, form[key])
        }
      }
    },
    /**
         * 重置数据状态
         */
    resetDataStatus() {
      const dataStatus = {}

      function resetStatus(datas) {
        if (datas instanceof Array) { // data 为 null 的情况会报错，需要判断
          datas.forEach(e => {
            dataStatus[e.id] = {
              delete: 0,
              edit: 0
            }
            if (e.children) {
              resetStatus(e.children)
            }
          })
        }
      }

      resetStatus(crud.data)
      crud.dataStatus = dataStatus
    },
    /**
         * 获取数据状态
         * @param {Number | String} id 数据项id
         */
    getDataStatus(id) {
      return crud.dataStatus[id]
    },
    /**
         * 用于树形表格多选, 选中所有
         * @param selection
         */
    selectAllChange(selection) {
      // 如果选中的数目与请求到的数目相同就选中子节点，否则就清空选中
      if (selection && selection.length === crud.data.length) {
        selection.forEach(val => {
          crud.selectChange(selection, val)
        })
      } else {
        crud.findVM('presenter').$refs['table'].clearSelection()
      }
    },
    /**
         * 用于树形表格多选，单选的封装
         * @param selection
         * @param row
         */
    selectChange(selection, row) {
      // 如果selection中存在row代表是选中，否则是取消选中
      if (selection.find(val => {
        return val.id === row.id
      })) {
        if (row.children) {
          row.children.forEach(val => {
            crud.findVM('presenter').$refs['table'].toggleRowSelection(val, true)
            selection.push(val)
            if (val.children) {
              crud.selectChange(selection, val)
            }
          })
        }
      } else {
        crud.toggleRowSelection(selection, row)
      }
    },
    /**
     * 删除表格行
     */
    delRow(index, tableId) {
      if (crud.findVM('presenter').$refs['form'].model.orderStatus !== 'PASS') {
        const table = tableId || 'table'
        const tableData = crud.findVM('presenter').$refs[table].data
        if (!tableData[index].id) {
          Vue.delete(tableData, index)
          return
        }
        crud.crudMethod.removeDetail(tableData[index].id).then(res => {
          Vue.delete(tableData, index)
          Vue.prototype.$message.success('删除成功')
          crud.refresh()
        }).catch(err => {
          crud.refresh()
        })
      }
    },



    /**
     * 添加表格行
     */
    addRow(index) {
      if (crud.findVM('presenter').$refs['form'].model.orderStatus !== 'PASS') {
        const addRow = JSON.parse(JSON.stringify(crud.findVM('presenter').addRowData))
        addRow.containerNo = ''
        addRow.id = ''
        addRow.lockNo = ''
        addRow.weight = ''
        addRow.totalWeight = ''
        addRow.weighNo = ''
        addRow.weigh = ''
        addRow.weightDifference = ''
        addRow.beforeImage = ''
        addRow.afterImage = ''
        addRow.gpsCode = ''
        addRow.remark = ''
        addRow.index = (index + 1)
        crud.findVM('presenter').$refs['table'].data.push(addRow)
      }
    },
    /**
     * 根据商品信息设置详情数据
     */

    setRows(row, list, data, index) {
      // eslint-disable-next-line no-unused-vars
      const href = window.location.href

      const assignmentWarehouseList = ['wareBuyEnterDetail', 'wareOtherEnterDetail', 'wareSalesReturnDetail']
      if (assignmentWarehouseList.includes(crud.findVM('presenter').$options.name)) {
        row.storehouseName = data.storehouseName
        row.warehouseName = data.warehouseName
        row.storehouseId = data.storehouseId
        row.warehouseId = data.warehouseId
        row.locationId = data.locationId
        row.locationName = data.locationName
      }
      row.goodsName = data.goodsName
      row.goodsCode = data.goodsCode
      row.goodsId = parseInt(data.goodsId)
      row.barcode = data.barcode
      row.boxUnitId = data.boxUnitId
      row.boxUnitName = data.boxUnitName
      row.boxUnitCount = data.boxUnitCount
      row.boxUnitId = data.boxUnitId
      row.boxNum = data.boxNum
      row.mainNum = data.mainNum
      row.mainUnitName = data.mainUnitName
      row.mainUnitId = data.mainUnitId
      row.mainUnitCount = data.mainUnitCount
      row.mainUnitCode = data.mainUnitCode
      row.boxBarcode = data.boxBarcode
      row.batchNo = data.batchNo
      row.discountAmount = data.discountAmount
      row.discountRate = data.discountRate
      row.createTime = data.createTime
      row.createUserCode = data.createUserCode
      row.createUserId = data.createUserId
      row.createUserName = data.createUserName
      row.cutOffGoodsCount = data.cutOffGoodsCount
      row.effectGoodsCount = data.effectGoodsCount
      row.firstUnitCode = data.firstUnitCode
      row.firstUnitCount = data.firstUnitCount
      row.firstUnitId = data.firstUnitId
      row.firstUnitName = data.firstUnitName
      row.goodsBrandCode = data.goodsBrandCode
      row.goodsBrandId = data.goodsBrandId
      row.goodsBrandName = data.goodsBrandName
      row.goodsTagCode = data.goodsTagCode
      row.goodsTagId = data.goodsTagId
      row.goodsTypeCode = data.goodsTypeCode
      row.goodsTagName = data.goodsTagName
      row.goodsTypeId = data.goodsTypeId
      row.goodsTypeName = data.goodsTypeName
      row.helpSign = data.helpSign
      row.model = data.model
      row.seq = data.seq
      row.pickGoodsCount = data.pickGoodsCount
      row.orderCode = data.orderCode
      row.orderId = data.orderId
      row.remark = data.remark
      row.taxCode = data.taxCode
      row.taxId = data.taxId
      row.taxName = data.taxName
      row.taxRate = data.taxRate || 0
      row.updateTime = data.updateTime
      row.updateUserCode = data.updateUserCode
      row.updateUserId = data.updateUserId
      row.updateUserName = data.updateUserName
      row.effectGoodsCount = data.effectGoodsCount
      row.firstUnitCode = data.firstUnitCode
      row.firstUnitCount = data.firstUnitCount
      row.firstUnitId = data.firstUnitId
      row.firstUnitName = data.firstUnitName
      row.secondUnitCode = data.secondUnitCode
      row.secondUnitCount = data.secondUnitCount
      row.secondUnitId = data.secondUnitId
      row.secondUnitName = data.secondUnitName
      row.priceType = data.priceType
      row.boxCount = data.boxCount
      row.thirdUnitCode = data.thirdUnitCode
      row.thirdUnitCount = data.thirdUnitCount
      row.thirdUnitId = data.thirdUnitId
      row.thirdUnitName = data.thirdUnitName

      row.fourthUnitCode = data.fourthUnitCode
      row.fourthUnitCount = data.fourthUnitCount
      row.fourthUnitId = data.fourthUnitId
      row.fourthUnitName = data.fourthUnitName

      row.minSaleUnitCode = data.minSaleUnitCode
      row.minSaleUnitCount = data.minSaleUnitCount
      row.minSaleUnitId = data.minSaleUnitId
      row.minSaleUnitName = data.minSaleUnitName

      row.minReturnUnitCode = data.minReturnUnitCode
      row.minReturnUnitCount = data.minReturnUnitCount
      row.minReturnUnitId = data.minReturnUnitId
      row.minReturnUnitName = data.minReturnUnitName
      row.discountRate = data.discountRate
      row.boxCount = data.boxCount
      row.discountRate = data.discountRate
      row.promotionType = data.promotionType
      row.outStorehouseName = data.outStorehouseName
      row.inStorehouseName = data.inStorehouseName
      row.outProducedDate = data.outProducedDate
      row.outDeadlineDate = data.outDeadlineDate
      row.inProducedDate = data.inProducedDate
      row.inDeadlineDate = data.inDeadlineDate
      row.occupyNum = data.occupyNum
      row.occupyBox = data.occupyBox
      row.existNum = data.existNum
      row.existBox = data.existBox
      row.existMainNum = data.existMainNum
      row.paperNum = data.paperNum
      row.paperBoxNum = data.paperBoxNum
      row.paperMainNum = data.paperMainNum
      row.boxCount = data.boxCount
      row.oldGoodsCount = data.goodsCount
      row.oldMainNum = data.mainNum
      row.oldBoxNum = data.boxNum

      row.profitLossBox = data.profitLossBox
      row.profitLossNum = data.profitLossNum
      row.profitLossMainNum = data.profitLossMainNum
      row.deadlineDate = data.deadlineDate
      row.producedDate = data.producedDate
      row.boxCount = data.boxCount
      row.oldMainNum = data.oldMainNum

      row.oldBoxNum = data.oldBoxNum
      row.weight = data.weight
      row.volume = data.volume
      row.packageType = data.packageType

      row.isPromotion = data.isPromotion
      row.goodsCount = data.goodsCount || 0
      row.effectGoodsCount = data.effectGoodsCount
      row.cutOffGoodsCount = data.cutOffGoodsCount
      row.boxTaxPrice = data.boxTaxPrice
      row.boxNoTaxPrice = data.boxNoTaxPrice
      row.sourceCode = data.sourceCode
      row.pickNum = data.pickNum || 0
      row.pickMainNum = data.pickMainNum
      row.pickBoxNum = data.pickBoxNum
      row.pickBoxCount = data.pickBoxCount
      row.sourceDetailType = data.sourceDetailType
      row.isPromotion = data.isPromotion
      row.promotionId = data.promotionId
      row.promotionCode = data.promotionCode
      row.promotionName = data.promotionName
      row.promotionType = data.promotionType
      row.promotionStartDate = data.promotionStartDate
      row.promotionEndDate = data.promotionEndDate
      row.promotionTaxPrice = data.promotionTaxPrice
      row.promotionTaxBoxPrice = data.promotionTaxBoxPrice
      row.effectGoodsCount = data.effectGoodsCount
      row.cutOffGoodsCount = data.cutOffGoodsCount
      row.saleTaxPrice = data.saleTaxPrice
      row.outLocationId = data.outLocationId
      row.outLocationCode = data.outLocationCode
      row.outLocationName = data.outLocationName
      row.inLocationId = data.inLocationId
      row.inLocationCode = data.inLocationCode
      row.inLocationName = data.inLocationName
      row.boxNum = data.boxNum || 0
      row.mainNum = data.mainNum || 0
      row.outStorehouseCode = data.outStorehouseCode
      row.outStorehouseId = data.outStorehouseId
      row.outStorehouseName = data.outStorehouseName
      row.inStorehouseName = data.inStorehouseName
      row.inStorehouseCode = data.inStorehouseCode
      row.inStorehouseId = data.inStorehouseId
      row.boxUnitId = data.boxUnitId
      row.boxUnitName = data.boxUnitName
      row.taxAmount = data.taxAmount || 0
      row.noTaxAmount = data.noTaxAmount || 0
      // eslint-disable-next-line eqeqeq
      if (row.isPromotion == 1) {
        if (row.goodsCount <= row.cutOffGoodsCount && row.goodsCount >= row.effectGoodsCount) {
          row.taxPrice = data.promotionTaxPrice
          row.noTaxPrice = data.promotionNoTaxPrice
          row.taxPrice = data.promotionTaxPrice
          row.oldTaxPrice = data.promotionTaxPrice
          row.oldTaxBoxPrice = data.promotionTaxBoxPrice
          row.noTaxBoxPrice = data.promotionNoTaxBoxPrice
          row.noTaxBoxPrice = data.promotionNoTaxBoxPrice
          row.taxBoxPrice = data.promotionTaxBoxPrice
        } else if (row.promotionType == 1 && row.cutOffGoodsCount == 0) {
          row.taxPrice = data.promotionTaxPrice
          row.noTaxPrice = data.promotionNoTaxPrice
          row.taxPrice = data.promotionTaxPrice
          row.oldTaxPrice = data.promotionTaxPrice
          row.oldTaxBoxPrice = data.promotionTaxBoxPrice
          row.noTaxBoxPrice = data.promotionNoTaxBoxPrice
          row.noTaxBoxPrice = data.promotionNoTaxBoxPrice
          row.taxBoxPrice = data.promotionTaxBoxPrice
        } else if (row.promotionType == 1 && row.cutOffGoodsCount > 0 && row.goodsCount <= row.cutOffGoodsCount) {
          row.taxPrice = data.promotionTaxPrice
          row.noTaxPrice = data.promotionNoTaxPrice
          row.taxPrice = data.promotionTaxPrice
          row.oldTaxPrice = data.promotionTaxPrice
          row.oldTaxBoxPrice = data.promotionTaxBoxPrice
          row.noTaxBoxPrice = data.promotionNoTaxBoxPrice
          row.noTaxBoxPrice = data.promotionNoTaxBoxPrice
          row.taxBoxPrice = data.promotionTaxBoxPrice
        } else {
          row.taxPrice = data.taxPrice
          row.noTaxPrice = data.noTaxPrice
          row.taxPrice = data.taxPrice
          row.oldTaxPrice = data.taxPrice
          row.oldTaxBoxPrice = data.taxBoxPrice
          row.noTaxBoxPrice = data.noTaxBoxPrice
          row.noTaxBoxPrice = data.noTaxBoxPrice
          row.taxBoxPrice = data.taxBoxPrice
          row.taxBoxPrice = data.taxBoxPrice
        }
      } else {
        row.taxPrice = data.taxPrice
        row.noTaxPrice = data.noTaxPrice
        row.taxPrice = data.taxPrice
        row.oldTaxPrice = data.taxPrice
        row.oldTaxBoxPrice = data.taxBoxPrice
        row.noTaxBoxPrice = data.noTaxBoxPrice
        row.noTaxBoxPrice = data.noTaxBoxPrice
        row.taxBoxPrice = data.taxBoxPrice
        row.taxBoxPrice = data.taxBoxPrice
      }
      let ids = null

      try {
        const contents = JSON.parse(localStorage.getItem('pageDatas')).content
        if (contents[index].id) {
          ids = contents[index].id
        }
        row.ids = ids
        list.map(item => {
          row[item] = data[item]
        })
        // eslint-disable-next-line no-empty
      } catch (e) {

      }
    },
    /**
     * 合计行
     */
    sumAuxiliaryCount(boxNum, mainNum) {
      const sum = ''
      let boxNumSum = 0
      let mainNumsum = 0
      if (crud.data) {
        for (const i in crud.data) {
          boxNumSum += Number(crud.data[i][boxNum])
          mainNumsum += Number(crud.data[i][mainNum])
        }
      }
      return `${boxNumSum}箱${mainNumsum}瓶`
    },
    sumSelectAuxiliaryCount(boxNum, mainNum) {
      const sum = ''
      let boxNumSum = 0
      let mainNumsum = 0
      for (const i in crud.selections) {
        console.log(crud.data[i][boxNum])
        boxNumSum += Number(crud.selections[i][boxNum])
        mainNumsum += Number(crud.selections[i][mainNum])
      }
      return `${boxNumSum}箱${mainNumsum}瓶`
    },
    /**
     * 合计行
     */
    getSummaries({ columns }) {
      const summaryData = crud.summaryData || crud.findVM('presenter').summaryData
      const sums = []
      const summaryList = ['boxCount', 'taxAmount', 'productCount', 'totalGrossWeight', 'totalNetWeight', 'count', 'noTaxAmount']
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        if (crud.selections.length > 0) {
          crud.selections.map(sel => {
            for (const key in sel) {
              if (column.property === key) {
                if (summaryList.includes(key)) {
                  sums[index] = (parseFloat(sel[key]) + (parseFloat(sums[index] || 0))).toFixed(2)
                }
              }
            }
          })
          return sums
        }
        for (const key in summaryData) {
          if (column.property === key) {
            sums[index] = summaryData[key]
          }
        }
      })
      return sums
    },
    sumRow(param) {
      const { columns, data } = param
      const sums = []
      const summaryList = ['boxCount', 'taxAmount', 'productCount', 'totalGrossWeight', 'totalNetWeight', 'count', 'noTaxAmount',
        'discountAmount', 'acceptBoxCount', 'acceptGoodsCount', 'acceptTaxAmount', 'acceptTax', 'cancelAmount', 'unCancelAmount', 'goodsCount',
        'checkGoodsCount', 'inAmount', 'balanceAmount', 'tax', 'acceptBoxNum', 'acceptMainNum', 'acceptNoTaxAmount', 'enterGoodsCount',
        'enterBoxCount', 'enterBoxNum', 'enterMainNum', 'enterTaxAmount', 'enterNoTaxAmount', 'enterTax', 'returnGoodsCount', 'returnBoxCount',
        'returnBoxNum', 'returnMainNum', 'returnTaxAmount', 'returnNoTaxAmount', 'returnTax', 'sendGoodsCount', 'sendBoxCount', 'sendBoxNum',
        'sendMainNum', 'sendTaxAmount', 'sendNoTaxAmount', 'sendTax', 'returnBottleBoxGoodsCount', 'returnBottleBoxBoxCount', 'returnBottleBoxBoxNum',
        'returnBottleBoxMainNum', 'returnBottleBoxTaxAmount', 'returnBottleBoxNoTaxAmount', 'returnBottleBoxTax', 'buyGoodsCount', 'buyBoxCount',
        'buyBoxNum', 'buyMainNum', 'buyTaxAmount', 'buyNoTaxAmount', 'buyTax', 'saleGoodsCount', 'saleBoxCount', 'saleBoxNum', 'saleMainNum',
        'saleTaxAmount', 'saleNoTaxAmount', 'saleTax', 'allotGoodsCount', 'form.allotBoxCount', 'allotBoxNum', 'allotMainNum', 'allotTaxAmount',
        'allotNoTaxAmount', 'allotTax', 'lossGoodsCount', 'lossBoxCount', 'lossBoxNum', 'lossMainNum', 'lossTaxAmount', 'lossNoTaxAmount', 'lossTax',
        'overGoodsCount', 'overBoxCount', 'overBoxNum', 'overMainNum', 'overTaxAmount', 'overNoTaxAmount', 'overTax', 'allotBoxCount', 'emptyBoxTaxAmount',
        'returnBoxTaxAmount', 'receiveAmount', 'receiptAmount', 'fuckNum', 'boxUnitId', 'existNum', 'usableNum', 'waitSendNum', 'expectUsableNum', 'pickNum',
        'loadBoxCount', 'salesReturnBoxCount', 'returnBottleBoxCount', 'returnBoxRate', 'loadInvoiceCount', 'salesInvoiceCount', 'feeAmount', 'loanAmount', 'repayAmount', 'unRepayAmount',
        'returnBoxTaxAmount', 'receiveAmount', 'receiptAmount', 'fuckNum', 'boxUnitId', 'existNum', 'usableNum', 'waitSendNum', 'expectUsableNum', 'pickNum', 'loadBoxCount', 'salesReturnBoxCount', 'returnBottleBoxCount', 'returnBoxRate', 'loadInvoiceCount', 'salesInvoiceCount', 'feeAmount', 'salesReceiveAmount', 'plasticBoxAmount', 'returnBoxAmount', 'actualReceiveAmount', 'overDateAmount', 'normalAmount', 'curAmount', 'beginAmount', 'actualAmount', 'beginGoodsCount', 'beginBoxCount', 'beginTaxAmount', 'beginNoTaxAmount', 'endGoodsCount', 'endTaxAmount', 'endBoxCount', 'costTaxPrice', 'buyInGoodsCount', 'buyInBoxCount', 'buyInTaxAmount', 'buyInNoTaxAmount', 'buyOutGoodsCount', 'buyOutBoxCount', 'buyOutTaxAmount', 'buyOutNoTaxAmount', 'saleInGoodsCount', 'saleInBoxCount', 'saleInTaxAmount', 'saleInNoTaxAmount', 'saleOutGoodsCount', 'saleOutBoxCount', 'saleOutTaxAmount', 'saleOutNoTaxAmount', 'allotInGoodsCount', 'allotInBoxCount', 'allotInTaxAmount', 'allotInNoTaxAmount', 'allotOutGoodsCount', 'allotOutBoxCount', 'allotOutTaxAmount', 'allotOutNoTaxAmount', 'incomeGoodsCount', 'incomeBoxCount', 'incomeTaxAmount', 'incomeNoTaxAmount', 'boxUnitCount', 'taxBoxPrice', 'noTaxBoxPrice', 'noTaxPrice', 'taxPrice'
      ]
      const auxiliaryList = ['boxNum', 'fuckNum', 'inBoxNum', 'initBoxNum', 'outBoxNum', 'existBoxNum', 'usableBoxNum',
        'onWayBoxNum', 'pickBoxNum', 'waitSendBoxNum', 'allotOutBoxNum', 'allotInBoxNum']
      // 'endBoxCount'
      columns.forEach((column, index) => {
        let selectSum = 0
        if (index === 0) {
          sums[index] = <p>
            选中合计
            <hr />
            合计
          </p>
          column.colSpan = 2
          return
        }
        if (auxiliaryList.includes(column.property)) {
          let sum, selectSum
          switch (column.property) {
            case 'boxNum':
              sum = crud.sumAuxiliaryCount('boxNum', 'mainNum')
              selectSum = crud.sumSelectAuxiliaryCount('boxNum', 'mainNum')
              sums[index - 1] = <p>{selectSum}<hr />{sum}</p>
              return sums
            case 'fuckNum':
              sum = crud.sumAuxiliaryCount('boxNum', 'mainNum')
              selectSum = crud.sumSelectAuxiliaryCount('boxNum', 'mainNum')
              sums[index - 1] = <p>{selectSum}<hr />{sum}</p>
              return sums
            default:
              const name = column.property.split('BoxNum')[0]
              sum = crud.sumAuxiliaryCount(`${name}BoxNum`, `${name}MainNum`)
              selectSum = crud.sumSelectAuxiliaryCount(`${name}BoxNum`, `${name}MainNum`)
              sums[index - 1] = <p>{selectSum}<hr />{sum}</p>
              return sums
          }
        }
        if (crud.selections.length > 0) {
          crud.selections.map(sel => {
            for (const key in sel) {
              if (column.property === key && summaryList.includes(key)) {
                selectSum += Number(sel[key]) || 0
              }
            }
          })
        }
        if (summaryList.includes(column.property)) { // 指定哪一列合计 如果需要全部合计 去掉这个判断即可
          const values = data.map((item) => Number(item[column.property]))
          if (!values.every((value) => isNaN(value))) {
            const sum = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                const sum = prev + curr
                return sum
              } else {
                return prev
              }
            }, 0)
            sums[index - 1] = <p>{selectSum}<hr /> {sum.toFixed(2)}</p>
          } else {
            sums[index - 1] = ''
          }
        }
      })
      return sums
    },

    /**
     * 获取当前节点及子节点
     */
    getNode(node, str) {
      if (node.children) {
        for (let i = 0; i < node.children.length; i++) {
          str = crud.getNode(node.children[i], str)
        }
      }
      return str += node.id + ','
    },

    /**
     * 给table每行加上index
     */
    tableRowClassName({ row, rowIndex }) {
      row.index = rowIndex
    },
    // 排序
    sortChange({ order, prop }) {
      const desc = order.split('ending')[0]
      crud.sort = prop + ',' + desc
      crud.refresh()
    },
    /**
     * 双击表格
     */
    dbClick(row) {
      if (crud.findVM('presenter').$refs['form'].model.orderStatus !== 'PASS') {
        row.isSelected = !row.isSelected
        const data = crud.findVM('presenter').$refs['table'].data
        Vue.set(data, row.index, data[row.index])
      }
    },
    /**
     * 复制
     */
    toCopy(event, url) {
      crud.findVM('presenter').$router.push({ path: url + '/copyId=' + event })
    },
    toGetCopyInfo(event, type) {
      crud.copyLoading = true
      const ids = []
      if (event) {
        ids.push(event)
      } else {
        const _datas = crud.selections
        // 获取选中的内容
        _datas.forEach(o => {
          ids.push(o.id)
        })
      }
      crud.crudMethod.copy(ids.join(',')).then((res) => {
        if (type === 'salesPromotionDetail') {
          crud.copyLoading = false
          crud.order = res.data.order
          crud.data = res.data.content
          crud.resetForm()
          Vue.prototype.$message.success('复制成功')
        } else {
          crud.copyLoading = false
          crud.order = res.data
          crud.data = res.data.detailList
          crud.resetForm()
          Vue.prototype.$message.success('复制成功')
        }
      }).catch(() => {
        crud.copyLoading = false
        callVmHook(crud, CRUD.HOOK.afterEditError)
        Vue.prototype.$message.error('复制失败，稍后再试')
      })
    },
    noPass(id) {
      ignorePromotionPass(id).then(res => {
        Vue.prototype.$message.success(res.msg)
        crud.refresh()
      })
    },
    /**
     * 超级审核
     */
    toSuperPass(id) {
      crud.enableOrDisableLoading = true
      const ids = []
      crud.loadingOpen()
      const _datas = crud.selections
      // 获取选中的内容
      console.log(typeof id)
        if (typeof id === 'string' || typeof id === 'number'){
        const href = location.href.split('/')
        if (href[5].includes('copyId')) {
          const strs = id.split('=')
          ids.push(strs[1])
        } else {
          ids.push(id)
        }
      }else{
          _datas.forEach(o => {
            ids.push(o.id)
          })

      }
      crud.crudMethod.superPass(ids).then(() => {
        crud.enableOrDisableLoading = false
        crud.resetForm()
        Vue.prototype.$message.success('超级审核成功')
        callVmHook(crud, CRUD.HOOK.afterSubmit)
        crud.refresh()
        crud.loadingClose()
      }).catch(() => {
        crud.enableOrDisableLoading = false
        callVmHook(crud, CRUD.HOOK.afterEditError)
        Vue.prototype.$message.error('超级审核失败，稍后再试')
        crud.loadingClose()
      })
    },
    /**
     * 复制为退货
     */
    toCopyToReturn(event) {
      crud.copyToReturnLoading = true
      const ids = []
      const _datas = crud.selections
      // 获取选中的内容
      _datas.forEach(o => {
        ids.push(Number(o.id))
      })
      crud.crudMethod.copyToReturn({ id: ids.join(','), warehouseId: event.warehouseId }).then(() => {
        crud.copyToReturnLoading = false
        crud.resetForm()
        Vue.prototype.$message.success('复制退货成功')
        callVmHook(crud, CRUD.HOOK.afterSubmit)
        crud.refresh()
      }).catch(() => {
        crud.copyToReturnLoading = false
        callVmHook(crud, CRUD.HOOK.afterEditError)
        // Vue.prototype.$message.error('复制退货失败，稍后再试')
      })
    },
    toCopyToReturnPlus(event, id) {
      crud.copyToReturnLoading = true
      const ids = []
      ids.push(Number(id))
      crud.crudMethod.copyToReturn({ id: ids.join(','), warehouseId: event.warehouseId }).then(() => {
        crud.copyToReturnLoading = false
        crud.resetForm()
        Vue.prototype.$message.success('复制退货成功')
        callVmHook(crud, CRUD.HOOK.afterSubmit)
        crud.refresh()
      }).catch(() => {
        crud.copyToReturnLoading = false
        callVmHook(crud, CRUD.HOOK.afterEditError)
        // Vue.prototype.$message.error('复制退货失败，稍后再试')
      })
    },
    getValue(e) {
      this.query.startTime = this.query.dataExtent[0]
      this.query.endTime = this.query.dataExtent[1]
    },
    saleToAccept(event, exchangeWarehouseId = null) {
      crud.acceptLoading = true
      const ids = []
      if (event) {
        const href = location.href.split('/')
        if (href[5].includes('copyId')) {
          const strs = event.split('=')
          ids.push(strs[1])
        } else {
          ids.push(event)
        }
      } else {
        const _datas = crud.selections
        // 获取选中的内容
        _datas.forEach(o => {
          ids.push(o.id)
        })
      }
      crud.crudMethod.accept({
        ids,
        exchangeWarehouseId
      }).then(() => {
        crud.acceptLoading = false
        crud.resetForm()
        Vue.prototype.$message.success('验收成功')
        callVmHook(crud, CRUD.HOOK.afterSubmit)
        crud.refresh()
      }).catch(() => {
        crud.acceptLoading = false
        callVmHook(crud, CRUD.HOOK.afterEditError)
        Vue.prototype.$message.error('验收失败，稍后再试')
      })
    },
    /**
     * 验收
     */
    toAccept(event) {
      crud.acceptLoading = true
      const ids = []
      if (event) {
        const href = location.href.split('/')
        if (href[5].includes('copyId')) {
          const strs = event.split('=')
          ids.push(strs[1])
        } else {
          ids.push(event)
        }
      } else {
        const _datas = crud.selections
        // 获取选中的内容
        _datas.forEach(o => {
          ids.push(o.id)
        })
      }
      crud.crudMethod.accept(ids).then(() => {
        crud.acceptLoading = false
        crud.resetForm()
        Vue.prototype.$message.success('验收成功')
        callVmHook(crud, CRUD.HOOK.afterSubmit)
        crud.refresh()
      }).catch(() => {
        crud.acceptLoading = false
        callVmHook(crud, CRUD.HOOK.afterEditError)
        Vue.prototype.$message.error('验收失败，稍后再试')
      })
    },
    /**
     * 取消验收
     */
    toUnAccept(event) {
      crud.acceptLoading = true
      const ids = []
      if (event) {
        const href = location.href.split('/')
        if (href[5].includes('copyId')) {
          const strs = event.split('=')
          ids.push(strs[1])
        } else {
          ids.push(event)
        }
      } else {
        const _datas = crud.selections
        // 获取选中的内容
        _datas.forEach(o => {
          ids.push(o.id)
        })
      }
      crud.crudMethod.unAccept(ids).then(() => {
        crud.acceptLoading = false
        crud.resetForm()
        Vue.prototype.$message.success('取消验收成功')
        callVmHook(crud, CRUD.HOOK.afterSubmit)
        crud.refresh()
      }).catch(() => {
        crud.acceptLoading = false
        callVmHook(crud, CRUD.HOOK.afterEditError)
        Vue.prototype.$message.error('取消验收失败，稍后再试')
      })
    },
    /**
     * 库存解锁
     */
    toUnLockStock(event) {
      crud.lockStockLoading = true
      const ids = []
      if (event) {
        const href = location.href.split('/')
        if (href[5].includes('copyId')) {
          const strs = event.split('=')
          ids.push(strs[1])
        } else {
          ids.push(event)
        }
      } else {
        const _datas = crud.selections
        // 获取选中的内容
        _datas.forEach(o => {
          ids.push(o.id)
        })
      }
      crud.crudMethod.unLockStock(ids).then(() => {
        crud.lockStockLoading = false
        crud.resetForm()
        Vue.prototype.$message.success('库存解锁成功')
        callVmHook(crud, CRUD.HOOK.afterSubmit)
        crud.refresh()
      }).catch(() => {
        crud.lockStockLoading = false
        callVmHook(crud, CRUD.HOOK.afterEditError)
        Vue.prototype.$message.error('库存解锁失败，稍后再试')
      })
    },
    /**
     * 库存加锁
     */
    toLockStock(event) {
      crud.lockStockLoading = true
      const ids = []
      if (event) {
        const href = location.href.split('/')
        if (href[5].includes('copyId')) {
          const strs = event.split('=')
          ids.push(strs[1])
        } else {
          ids.push(event)
        }
      } else {
        const _datas = crud.selections
        // 获取选中的内容
        _datas.forEach(o => {
          ids.push(o.id)
        })
      }
      crud.crudMethod.lockStock(ids).then(() => {
        crud.lockStockLoading = false
        crud.resetForm()
        Vue.prototype.$message.success('库存加锁成功')
        callVmHook(crud, CRUD.HOOK.afterSubmit)
        crud.refresh()
      }).catch(() => {
        crud.lockStockLoading = false
        callVmHook(crud, CRUD.HOOK.afterEditError)
        Vue.prototype.$message.error('库存加锁失败，稍后再试')
      })
    },
    /**
     * 单据拆分
     */
    toSplit(event) {
      crud.acceptLoading = true
      const orderId = []
      const ids = []
      if (event) {
        const href = location.href.split('/')
        if (href[5].includes('copyId')) {
          const strs = id.split('=')
          orderId.push(Number(strs[1]))
        } else {
          orderId.push(Number(event))
        }
        const _datas = crud.selections
        // 获取选中的内容
        _datas.forEach(o => {
          ids.push(o.id)
        })
      } else {
        const _datas = crud.selections
        // 获取选中的内容
        _datas.forEach(o => {
          orderId.push(Number(o.id))
          if (o.detailList) {
            o.detailList.map((item) => {
              ids.push(item.id)
            })
          }
        })
      }
      crud.crudMethod.split({ orderId: orderId.join(','), ids }).then(() => {
        crud.acceptLoading = false
        crud.resetForm()
        Vue.prototype.$message.success('拆分成功')
        callVmHook(crud, CRUD.HOOK.afterSubmit)
        crud.refresh()
      }).catch(() => {
        crud.acceptLoading = false
        callVmHook(crud, CRUD.HOOK.afterEditError)
        Vue.prototype.$message.error('拆分失败，稍后再试')
      })
    },
    /**
     * 导出详情
     */
    toExportDetail(event) {
      crud.downloadDetailLoading = true
      crud.query.orderIds = ''
      crud.query.ids = ''
      crud.selections.forEach(item => {
        crud.query.orderIds += item.id + ','
      })
      const params = crud.getQueryParams()
      // if (event) {
      //   params.ids = event
      // } else {
      //   if (crud.selections) {
      //     params.ids = crud.selections.map(row => row.id).join()
      //   }
      // }
      download(crud.url + '/exportDetail', params).then(result => {
        downloadFile(result, crud.title + '数据', 'xlsx')
        crud.downloadDetailLoading = false
      }).catch(() => {
        crud.downloadDetailLoading = false
      })
    },
    /**
     * 详情数量数据改变
     */
    inuptCount({ row, $index }, key, callback = null) {
      const list = ['mainNum', 'mainNum', 'boxUnitId', 'goodsCount', 'taxPrice', 'boxNum', 'boxCount', 'productCount', 'totalGrossWeight', 'totalNetWeight', 'detailNum', 'count', 'taxPrice']
      if (row.goodsId) {
        const product_type = row.priceType || ''

        var boxCount = Number(row.goodsCount || 0) / Number(row.boxUnitCount || 0)

        if (key == 'taxPrice') {
          if (product_type == 'SINGLE') {
            row.taxBoxPrice = Number(row.taxPrice || 0) * Number(row.boxUnitCount || 0).toFixed(6)
            row.noTaxPrice = Number(row.taxPrice || 0) / (1 + Number(row.taxRate || 0) / 100).toFixed(6)
            row.noTaxBoxPrice = Number(row.taxBoxPrice || 0) / (1 + Number(row.taxRate || 0) / 100).toFixed(6)
            row.taxAmount = Number(row.taxPrice || 0) * Number(row.goodsCount || 0).toFixed(6)
            row.noTaxAmount = Number(row.noTaxPrice || 0) * Number(row.goodsCount || 0).toFixed(6)
            row.tax = Number(row.taxAmount || 0) - Number(row.noTaxAmount || 0).toFixed(6)
          } else {
            row.taxBoxPrice = Number(row.taxPrice || 0) * Number(row.boxUnitCount || 0).toFixed(6)
            row.noTaxPrice = Number(row.taxPrice || 0) / (1 + Number(row.taxRate || 0) / 100).toFixed(6)
            row.noTaxBoxPrice = Number(row.taxBoxPrice || 0) / (1 + Number(row.taxRate || 0) / 100).toFixed(6)
            row.taxAmount = Number(row.taxBoxPrice || 0) * Number(boxCount || 0).toFixed(6)
            row.noTaxAmount = Number(row.noTaxPrice || 0) * Number(row.goodsCount || 0).toFixed(6)
            row.tax = Number(row.taxAmount || 0) - Number(row.noTaxAmount || 0).toFixed(6)
          }
          row.billTaxPrice = row.taxPrice
          row.billTaxBoxPrice = row.taxBoxPrice
          // row.discountRate = Number(row.taxPrice || 0) / Number(row.oldTaxPrice || 0) || 0
        } else if (key == 'taxBoxPrice') {
          if (product_type == 'SINGLE') {
            row.taxPrice = (Number(row.taxBoxPrice || 0) / (Number(row.boxUnitCount || 0))).toFixed(6)
            row.noTaxPrice = (Number(row.taxPrice || 0) / (1 + Number(row.taxRate || 0) / 100)).toFixed(6)
            row.noTaxBoxPrice = (Number(row.taxBoxPrice || 0) / (1 + Number(row.taxRate || 0) / 100)).toFixed(6)
            row.taxAmount = (Number(row.taxPrice || 0) * Number(row.goodsCount || 0)).toFixed(6)
            row.noTaxAmount = (Number(row.noTaxPrice || 0) * Number(row.goodsCount || 0)).toFixed(6)
            row.tax = (Number(row.taxAmount || 0) - Number(row.noTaxAmount || 0)).toFixed(6)
            row.discountRate = (Number(row.taxBoxPrice || 0) / Number(row.oldTaxBoxPrice || 0)).toFixed(6)
            row.discountAmount = (Number(row.oldTaxPrice || 0) * Number(row.goodsCount || 0) - Number(row.taxAmount || 0)).toFixed(6)
          } else {
            row.taxPrice = (Number(row.taxBoxPrice || 0) / (Number(row.boxUnitCount || 0))).toFixed(6)
            // row.taxBoxPrice = (Number(row.taxPrice || 0) * Number(row.boxUnitCount || 0)).toFixed(2)
            row.noTaxPrice = (Number(row.taxPrice || 0) / (1 + Number(row.taxRate || 0) / 100)).toFixed(6)
            row.noTaxBoxPrice = (Number(row.taxBoxPrice || 0) / (1 + Number(row.taxRate || 0) / 100)).toFixed(6)
            row.noTaxAmount = (Number(row.noTaxPrice || 0 * boxCount || 0)).toFixed(6)
            row.taxAmount = (Number(row.taxPrice || 0) * Number(row.goodsCount || 0)).toFixed(6)
            row.tax = (Number(row.taxAmount || 0) - Number(row.noTaxAmount || 0)).toFixed(6)
          }
          row.billTaxPrice = row.taxPrice
          row.billTaxBoxPrice = row.taxBoxPrice
        } else if (key == 'discountRate') {
          row.taxPrice = (Number(row.oldTaxPrice) * (Number(row.discountRate || 0) / 100)).toFixed(6)
          row.taxBoxPrice = (Number(row.oldTaxBoxPrice) * (Number(row.discountRate || 0) / 100)).toFixed(6)
          row.noTaxPrice = (Number(row.taxPrice || 0) / (1 + Number(row.taxRate || 0) / 100)).toFixed(6)
          row.noTaxBoxPrice = (Number(row.taxBoxPrice || 0) / (1 + Number(row.taxRate || 0)) / 100).toFixed(6)
          row.taxAmount = (Number(row.taxPrice || 0) * Number(row.goodsCount || 0)).toFixed(6)
          row.noTaxAmount = (Number(row.noTaxPrice || 0) * Number(row.goodsCount || 0)).toFixed(6)
          row.tax = (Number(row.taxAmount || 0) - Number(row.noTaxAmount || 0)).toFixed(6)
          row.discountAmount = (Number(row.oldTaxPrice || 0) * Number(row.goodsCount || 0) - Number(row.taxAmount || 0)).toFixed(6)
        } else if (key == 'mainNum' || key == 'boxNum') {
          row.goodsCount = (Number(row.boxUnitCount * row.boxNum || 0) + Number(row.mainUnitCount * row.mainNum || 0))
          row.boxCount = (Number(row.goodsCount || 0) / Number(row.boxUnitCount || 0)).toFixed(6)
          row.taxAmount = (Number(row.taxPrice || 0) * Number(row.goodsCount || 0)).toFixed(6)
          row.noTaxAmount = (Number(row.noTaxPrice || 0) * Number(row.goodsCount || 0)).toFixed(6)
          row.tax = (Number(row.taxAmount || 0) - Number(row.noTaxAmount || 0)).toFixed(6)
          row.discountAmount = (Number(row.oldTaxPrice || 0) * Number(row.goodsCount || 0) - Number(row.taxAmount || 0)).toFixed(6)
        } else if (key == 'goodsCount') {
          // if(Number(row.goodsCount)%Number(row.minSaleUnitCount) != 0){
          //   row.goodsCount = ''
          //   Vue.prototype.$message.error('请输入最小销售单位整数倍的数量')
          //   Vue.set(crud.data, $index, row)
          //   return false
          // }
          const info = parseInt(Number(row.goodsCount || 0) / Number(row.boxUnitCount || 0))
          row.boxNum = info
          if (row.boxUnitCount * info > row.goodsCount) {
            row.mainNum = (Number(row.boxUnitCount * info) - Number(row.goodsCount || 0))
          } else {
            row.mainNum = (Number(row.goodsCount || 0) - Number(row.boxUnitCount * info))
          }
        } else if (key == 'taxAmount') {
          row.taxPrice = (Number(row.taxAmount || 0) / Number(row.goodsCount || 0)).toFixed(6)
          row.taxBoxPrice = Number(row.taxPrice || 0) * Number(row.boxUnitCount || 0).toFixed(6)
          row.noTaxPrice = Number(row.taxPrice || 0) / (1 + Number(row.taxRate || 0) / 100).toFixed(6)
          row.noTaxBoxPrice = Number(row.taxBoxPrice || 0) / (1 + Number(row.taxRate || 0) / 100).toFixed(6)
          row.noTaxAmount = Number(row.noTaxPrice || 0) * Number(row.goodsCount || 0).toFixed(6)
          row.tax = Number(row.taxAmount || 0) - Number(row.noTaxAmount || 0).toFixed(6)
          row.billTaxPrice = row.taxPrice
          row.billTaxBoxPrice = row.taxBoxPrice
        }
        row.billTaxAmount = Number(row.billTaxPrice) * Number(row.goodsCount)
        //
        // row.volume = Number(row.goodsCount || 0) * Number(row.volume || 0)/Number(row.boxUnitCount || 0)
        // row.weight = Number(row.goodsCount || 0) * Number(row.weight || 0)/Number(row.boxUnitCount || 0)
        // if (product_type == 'SINGLE') {
        //   if (key == 'taxPrice') {
        //     row.taxBoxPrice = Number(row.taxPrice || 0) * Number(row.boxUnitCount || 0)
        //     row.noTaxPrice = Number(row.taxPrice || 0) / (1 + Number(row.taxRate || 0) / 100)
        //     row.noTaxBoxPrice = Number(row.taxBoxPrice || 0) / (1 + Number(row.taxRate || 0) / 100)
        //     row.taxAmount = Number(row.taxPrice || 0) * Number(row.goodsCount || 0)
        //     row.noTaxAmount = Number(row.noTaxPrice || 0) * Number(row.goodsCount || 0)
        //     row.tax = Number(row.taxAmount || 0) - Number(row.noTaxAmount || 0)
        //   } else if (key == 'noTaxPrice') {
        //     row.noTaxAmount = Number(row.noTaxPrice || 0 * row.goodsCount || 0)
        //   } else {
        //     // row.taxAmount = Number(row.taxPrice || 0 * row.goodsCount || 0)
        //     // row.noTaxAmount = Number(row.noTaxPrice || 0 * row.goodsCount || 0)
        //   }
        //   row.tax = Number(row.taxPrice * row.goodsCount || 0) - Number(row.noTaxPrice * row.goodsCount || 0)
        // } else if (product_type == 'BOX') {
        //   var boxCount = Number(row.goodsCount || 0) / Number(row.thirdUnitCount || 0)
        //   if (key == 'taxPrice') {
        //     row.taxAmount = Number(row.boxTaxPrice || 0 * boxCount || 0)
        //     row.taxBoxPrice = Number(row.taxPrice || 0) * Number(row.boxUnitCount || 0)
        //     row.noTaxPrice = Number(row.taxPrice || 0) / (1 + Number(row.taxRate || 0) / 100)
        //     row.noTaxBoxPrice = Number(row.taxBoxPrice || 0) / (1 + Number(row.taxRate || 0) / 100)
        //     row.noTaxAmount = Number(row.noTaxPrice || 0) * Number(row.goodsCount || 0)
        //     // row.tax = Number(row.taxAmount || 0) - Number(row.noTaxAmount || 0)
        //   }
        //   if (key == 'noTaxPrice') {
        //     row.noTaxAmount = Number(row.boxNoTaxPrice || 0 * boxCount || 0)
        //     row.taxBoxPrice = Number(row.taxPrice || 0) * Number(row.boxUnitCount || 0)
        //     row.noTaxPrice = Number(row.taxPrice || 0) / (1 + Number(row.taxRate || 0) / 100)
        //     row.noTaxBoxPrice = Number(row.taxBoxPrice || 0) / (1 + Number(row.taxRate || 0) / 100)
        //     row.taxAmount = Number(row.taxPrice || 0) * Number(row.goodsCount || 0)
        //     // row.tax = Number(row.taxAmount || 0) - Number(row.noTaxAmount || 0)
        //   }
        //   row.boxCount = boxCount
        //   // row.tax = Number(row.taxAmount || 0) - Number(row.noTaxAmount || 0)
        //   // row.tax = Number(row.taxPrice * row.goodsCount || 0) - Number(row.noTaxPrice * row.goodsCount || 0)
        // }
        // crud.loadingClose()
      } else {
        if (key == 'mainNum') {
          row.mainNum = row[key]
        } else if (key == 'boxNum') {
          row.boxNum = row[key]
        }
        if (key == 'goodsCount') {
          row.mainNum = ''
          row.boxNum = ''
        }
      }
      row.discountRate = (row.taxPrice / row.oldTaxPrice).toFixed(6) * 100
      Vue.set(crud.data, $index, row)
      if(callback != null){
        callback(row)
      }
      crud.findVM('presenter').$forceUpdate()

      // crud.loadingClose()
      // }, 1000)
    },
    setProduct(event, { row, $index }, name) {
      const table = crud.data
      // eslint-disable-next-line no-unused-vars
      const order = crud.order
      if (event) {
        if (name == 'warehouseName') {
          row.warehouseName = event.name
          row.storehouseId = ''
          row.storehouseName = ''
          row.warehouseId = event.id
        }
        if (name == 'storehouseName') {
          row.storehouseName = event.name
          row.storehouseId = event.id
        }
        if (name == 'goodsTagName') {
          row.goodsTagName = event.name
          row.goodsTagId = event.id
          if (event.isZeroPrice) {
            row.taxPrice = 0
            row.billTaxPrice = 0
            row.billTaxBoxPrice = 0
            row.billTaxAmount = 0
          } else {
            if (row.isPromotion === 1 && row.promotionType === '1' && !row.isZeroPrice) {
              if ((row.goodsCount <= row.cutOffGoodsCount && row.goodsCount >= row.effectGoodsCount) || row.cutOffGoodsCount === 0 || (row.cutOffGoodsCount > 0 && row.goodsCount <= row.cutOffGoodsCount)) {
                row.taxPrice = row.promotionTaxPrice
                row.taxBoxPrice = row.promotionTaxBoxPrice
              } else {
                row.taxPrice = row.oldTaxPrice
              }
            } else {
              row.taxPrice = row.oldTaxPrice
            }
          }
          row.taxBoxPrice = Number(row.taxPrice || 0) * Number(row.boxUnitCount || 0).toFixed(6)
          row.noTaxPrice = Number(row.taxPrice || 0) / (1 + Number(row.taxRate || 0) / 100).toFixed(6)
          row.noTaxBoxPrice = Number(row.taxBoxPrice || 0) / (1 + Number(row.taxRate || 0) / 100).toFixed(6)
          row.taxAmount = Number(row.taxPrice || 0) * Number(row.goodsCount || 0).toFixed(6)
          row.noTaxAmount = Number(row.noTaxPrice || 0) * Number(row.goodsCount || 0).toFixed(6)
          row.tax = Number(row.taxAmount || 0) - Number(row.noTaxAmount || 0).toFixed(6)
        }
        Vue.set(table, $index, row)
      }
    },
    /**
     * 详情商品数据改变
     */
    productChange(event, { row, $index }, name) {
      const table = crud.data
      const order = crud.order
      const list = ['totalGrossWeight', 'totalNetWeight', 'existNum', 'buyTaxPrice', 'material', 'model', 'taxPrice', 'taxPrice', 'bomCount', 'grossWeight', 'netWeight']
      if (event) {
        // 获取金额等信息
        // if (event.id && event.productCount) {
        //   event.productId = event.id
        //   const product_type = type || 'BUY'
        //   crud.getProductInfo(event, 'productCount', product_type).then(res => {
        //     list.map(item => {
        //       event[item] = res[item]
        //     })
        //     crud.setRow(row, list, event)
        //     Vue.set(table, $index, row)
        //   })
        //   return
        // row.volume = Number(row.goodsCount || 0) * Number(row.volume || 0)/Number(row.boxUnitCount || 0)
        // row.weight = Number(row.goodsCount || 0) * Number(row.weight || 0)/Number(row.boxUnitCount || 0)
        // }
        crud.setRows(row, list, event, $index)
        Vue.set(table, $index, row)
        return
      }
      const rows = {
        isSelected: true,
        warehouseId: row.warehouseId,
        warehouseName: row.warehouseName,
        taxAmount: row.taxAmount,
        bomCount: row.bomCount,
        existNum: row.existNum,
        occupyNum: row.occupyNum
      }
      Vue.set(table, $index, rows)
    },
    /**

     /**
     * 弹框商品数据改变
     */
    diaLogGoodsChange({ row, index, data }) {
      const table = crud.data
      // eslint-disable-next-line no-unused-vars
      const order = crud.order
      const list = ['totalGrossWeight', 'totalNetWeight', 'existNum', 'buyTaxPrice', 'material', 'model', 'taxPrice', 'taxPrice', 'bomCount', 'grossWeight', 'netWeight']
      // eslint-disable-next-line no-unused-vars
      const href = window.location.href
      const assignmentWarehouseList = ['wareBuyEnterDetail', 'wareOtherEnterDetail', 'wareSalesReturnDetail']
      if (assignmentWarehouseList.includes(crud.findVM('presenter').$options.name)) {
        row.storehouseName = data.storehouseName
        row.warehouseName = data.warehouseName
        row.storehouseId = data.storehouseId
        row.warehouseId = data.warehouseId
        row.locationId = data.locationId
        row.locationName = data.locationName
      }
      row.goodsName = data.goodsName
      row.goodsCode = data.goodsCode
      row.goodsId = parseInt(data.goodsId)
      row.barcode = data.barcode
      row.boxUnitId = data.boxUnitId
      row.boxUnitName = data.boxUnitName
      row.boxUnitCount = data.boxUnitCount
      row.boxUnitId = data.boxUnitId
      row.boxNum = data.boxNum
      row.mainNum = data.mainNum
      row.mainUnitName = data.mainUnitName
      row.mainUnitId = data.mainUnitId
      row.mainUnitCount = data.mainUnitCount
      row.mainUnitCode = data.mainUnitCode
      row.boxBarcode = data.boxBarcode
      row.batchNo = data.batchNo
      row.discountAmount = data.discountAmount
      row.discountRate = data.discountRate
      row.createTime = data.createTime
      row.createUserCode = data.createUserCode
      row.createUserId = data.createUserId
      row.createUserName = data.createUserName
      row.cutOffGoodsCount = data.cutOffGoodsCount
      row.effectGoodsCount = data.effectGoodsCount
      row.firstUnitCode = data.firstUnitCode
      row.firstUnitCount = data.firstUnitCount
      row.firstUnitId = data.firstUnitId
      row.firstUnitName = data.firstUnitName
      row.goodsBrandCode = data.goodsBrandCode
      row.goodsBrandId = data.goodsBrandId
      row.goodsBrandName = data.goodsBrandName
      row.goodsTagCode = data.goodsTagCode
      row.goodsTagId = data.goodsTagId
      row.goodsTypeCode = data.goodsTypeCode
      row.goodsTagName = data.goodsTagName
      row.goodsTypeId = data.goodsTypeId
      row.goodsTypeName = data.goodsTypeName
      row.helpSign = data.helpSign
      row.model = data.model
      row.seq = data.seq
      row.pickGoodsCount = data.pickGoodsCount
      row.orderCode = data.orderCode
      row.orderId = data.orderId
      row.remark = data.remark
      row.taxCode = data.taxCode
      row.taxId = data.taxId
      row.taxName = data.taxName
      row.taxRate = data.taxRate || 0
      row.updateTime = data.updateTime
      row.updateUserCode = data.updateUserCode
      row.updateUserId = data.updateUserId
      row.updateUserName = data.updateUserName
      row.effectGoodsCount = data.effectGoodsCount
      row.firstUnitCode = data.firstUnitCode
      row.firstUnitCount = data.firstUnitCount
      row.firstUnitId = data.firstUnitId
      row.firstUnitName = data.firstUnitName
      row.secondUnitCode = data.secondUnitCode
      row.secondUnitCount = data.secondUnitCount
      row.secondUnitId = data.secondUnitId
      row.secondUnitName = data.secondUnitName
      row.priceType = data.priceType
      row.boxCount = data.boxCount
      row.thirdUnitCode = data.thirdUnitCode
      row.thirdUnitCount = data.thirdUnitCount
      row.thirdUnitId = data.thirdUnitId
      row.thirdUnitName = data.thirdUnitName

      row.fourthUnitCode = data.fourthUnitCode
      row.fourthUnitCount = data.fourthUnitCount
      row.fourthUnitId = data.fourthUnitId
      row.fourthUnitName = data.fourthUnitName

      row.minSaleUnitCode = data.minSaleUnitCode
      row.minSaleUnitCount = data.minSaleUnitCount
      row.minSaleUnitId = data.minSaleUnitId
      row.minSaleUnitName = data.minSaleUnitName

      row.minReturnUnitCode = data.minReturnUnitCode
      row.minReturnUnitCount = data.minReturnUnitCount
      row.minReturnUnitId = data.minReturnUnitId
      row.minReturnUnitName = data.minReturnUnitName
      row.discountRate = data.discountRate
      row.boxCount = data.boxCount
      row.discountRate = data.discountRate
      row.promotionType = data.promotionType
      row.outStorehouseName = data.outStorehouseName
      row.inStorehouseName = data.inStorehouseName
      row.outProducedDate = data.outProducedDate
      row.outDeadlineDate = data.outDeadlineDate
      row.inProducedDate = data.inProducedDate
      row.inDeadlineDate = data.inDeadlineDate
      row.occupyNum = data.occupyNum
      row.occupyBox = data.occupyBox
      row.existNum = data.existNum
      row.existBox = data.existBox
      row.existMainNum = data.existMainNum
      row.paperNum = data.paperNum
      row.paperBoxNum = data.paperBoxNum
      row.paperMainNum = data.paperMainNum
      row.goodsCount = data.goodsCount
      row.boxCount = data.boxCount
      row.oldGoodsCount = data.goodsCount
      row.oldMainNum = data.mainNum
      row.oldBoxNum = data.boxNum

      row.profitLossBox = data.profitLossBox
      row.profitLossNum = data.profitLossNum
      row.profitLossMainNum = data.profitLossMainNum
      row.deadlineDate = data.deadlineDate
      row.producedDate = data.producedDate
      row.boxCount = data.boxCount
      row.oldMainNum = data.oldMainNum

      row.oldBoxNum = data.oldBoxNum
      row.weight = data.weight
      row.volume = data.volume
      row.packageType = data.packageType

      row.isPromotion = data.isPromotion
      row.effectGoodsCount = data.effectGoodsCount
      row.cutOffGoodsCount = data.cutOffGoodsCount
      row.boxTaxPrice = data.boxTaxPrice
      row.boxNoTaxPrice = data.boxNoTaxPrice
      row.sourceCode = data.sourceCode

      row.sourceDetailType = data.sourceDetailType
      row.promotionId = data.promotionId
      row.promotionCode = data.promotionCode
      row.promotionName = data.promotionName
      row.promotionType = data.promotionType
      row.promotionStartDate = data.promotionStartDate
      row.promotionEndDate = data.promotionEndDate
      row.promotionTaxPrice = data.promotionTaxPrice
      row.promotionTaxBoxPrice = data.promotionTaxBoxPrice
      row.effectGoodsCount = data.effectGoodsCount
      row.cutOffGoodsCount = data.cutOffGoodsCount
      row.saleTaxPrice = data.saleTaxPrice
      row.outLocationId = data.outLocationId
      row.outLocationCode = data.outLocationCode
      row.outLocationName = data.outLocationName
      row.inLocationId = data.inLocationId
      row.inLocationCode = data.inLocationCode
      row.inLocationName = data.inLocationName

      row.outStorehouseCode = data.outStorehouseCode
      row.outStorehouseId = data.outStorehouseId
      row.outStorehouseName = data.outStorehouseName
      row.inStorehouseName = data.inStorehouseName
      row.inStorehouseCode = data.inStorehouseCode
      row.inStorehouseId = data.inStorehouseId
      row.boxUnitId = data.boxUnitId
      row.boxUnitName = data.boxUnitName
      row.usableNum = data.usableNum
      row.usableBoxNum = data.usableBoxNum
      row.usableMainNum = data.usableMainNum
      row.billTaxPrice = data.billTaxPrice || data.taxPrice
      row.billTaxBoxPrice = data.billTaxBoxPrice || data.taxBoxPrice
      // const boxCount = parseInt(Number(data.usableNum)/Number(data.boxUnitCount))
      // const mainCount = data.usableNum%Number(data.boxUnitCount)
      // row.usableBoxNum = `${boxCount}${data.boxUnitName}${mainCount}${data.mainUnitName}`

      if (row.isPromotion == 1 && row.promotionType == 1) {
        if (row.goodsCount <= row.cutOffGoodsCount && row.goodsCount >= row.effectGoodsCount) {
          row.noTaxPrice = data.promotionNoTaxPrice
          row.taxPrice = data.promotionTaxPrice
          row.oldTaxPrice = data.promotionTaxPrice
          row.oldTaxBoxPrice = data.promotionTaxBoxPrice
          row.noTaxBoxPrice = data.promotionNoTaxBoxPrice
          row.noTaxBoxPrice = data.promotionNoTaxBoxPrice
          row.taxBoxPrice = data.promotionTaxBoxPrice
          row.remark = data.promotionRemark
        } else if (row.cutOffGoodsCount == 0) {
          row.taxPrice = data.promotionTaxPrice
          row.noTaxPrice = data.promotionNoTaxPrice
          row.taxPrice = data.promotionTaxPrice
          row.oldTaxPrice = data.promotionTaxPrice
          row.oldTaxBoxPrice = data.promotionTaxBoxPrice
          row.noTaxBoxPrice = data.promotionNoTaxBoxPrice
          row.noTaxBoxPrice = data.promotionNoTaxBoxPrice
          row.taxBoxPrice = data.promotionTaxBoxPrice
          row.remark = data.promotionRemark
        } else if (row.cutOffGoodsCount > 0 && row.goodsCount <= row.cutOffGoodsCount) {
          row.taxPrice = data.promotionTaxPrice
          row.noTaxPrice = data.promotionNoTaxPrice
          row.taxPrice = data.promotionTaxPrice
          row.oldTaxPrice = data.promotionTaxPrice
          row.oldTaxBoxPrice = data.promotionTaxBoxPrice
          row.noTaxBoxPrice = data.promotionNoTaxBoxPrice
          row.noTaxBoxPrice = data.promotionNoTaxBoxPrice
          row.taxBoxPrice = data.promotionTaxBoxPrice
          row.remark = data.promotionRemark
        } else {
          row.taxPrice = data.taxPrice
          row.noTaxPrice = data.noTaxPrice
          row.taxPrice = data.taxPrice
          row.oldTaxPrice = data.taxPrice
          row.oldTaxBoxPrice = data.taxBoxPrice
          row.noTaxBoxPrice = data.noTaxBoxPrice
          row.noTaxBoxPrice = data.noTaxBoxPrice
          row.taxBoxPrice = data.taxBoxPrice
          row.taxBoxPrice = data.taxBoxPrice
        }
      } else {
        row.taxPrice = data.taxPrice
        row.noTaxPrice = data.noTaxPrice
        row.taxPrice = data.taxPrice
        row.oldTaxPrice = data.taxPrice
        row.oldTaxBoxPrice = data.taxBoxPrice
        row.noTaxBoxPrice = data.noTaxBoxPrice
        row.noTaxBoxPrice = data.noTaxBoxPrice
        row.taxBoxPrice = data.taxBoxPrice
        row.taxBoxPrice = data.taxBoxPrice
      }

      Vue.set(table, index, row)

      // const rows = {
      //   isSelected: true,
      //   warehouseId: row.warehouseId,
      //   warehouseName: row.warehouseName,
      //   taxAmount: row.taxAmount,
      //   bomCount: row.bomCount,
      //   existNum: row.existNum,
      //   occupyNum: row.occupyNum
      // }
      // Vue.set(table, index, rows)
    },

    sortTab(row, before) {
      if (row.column.order) {
        crud.query.sort = `${row.column.property} ${row.column.order === 'ascending' ? 'asc' : 'desc'}`
      } else {
        try {
          this.query.sort = null
        } catch (e) {
          console.err(e)
        }
      }

      crud.toQuery()
    },
    /**

         * 切换选中状态
         * @param selection
         * @param data
         */
    toggleRowSelection(selection, data) {
      if (data.children) {
        data.children.forEach(val => {
          crud.findVM('presenter').$refs['table'].toggleRowSelection(val, false)
          if (val.children) {
            crud.toggleRowSelection(selection, val)
          }
        })
      }
    },
    findVM(type) {
      return crud.vms.find(vm => vm && vm.type === type).vm
    },
    notify(title, type = CRUD.NOTIFICATION_TYPE.INFO) {
      crud.vms[0].vm.$notify({
        title,
        type,
        duration: 2500
      })
    },
    updateProp(name, value) {
      Vue.set(crud.props, name, value)
    }
  }
  const crud = Object.assign({}, data)
  // 可观测化
  Vue.observable(crud)
  // 附加方法
  Object.assign(crud, methods)
  // 记录初始默认的查询参数，后续重置查询时使用
  Object.assign(crud, {
    defaultQuery: JSON.parse(JSON.stringify(data.query)),
    // 预留4位存储：组件 主页、头部、分页、表单，调试查看也方便找
    vms: Array(4),
    /**
         * 注册组件实例
         * @param {String} type 类型
         * @param {*} vm 组件实例
         * @param {Number} index 该参数内部使用
         */
    registerVM(type, vm, index = -1) {
      const vmObj = {
        type,
        vm: vm
      }
      if (index < 0) {
        this.vms.push(vmObj)
        return
      }
      this.vms.length = Math.max(this.vms.length, index)
      this.vms.splice(index, 1, vmObj)
    },
    /**
         * 取消注册组件实例
         * @param {*} vm 组件实例
         */
    unregisterVM(vm) {
      this.vms.splice(this.vms.findIndex(e => e && e.vm === vm), 1)
    },
    /**
     * 更新分页
     */
    toUpdateHeader() {
      const data = {
        name: crud.name,
        code: crud.headerInfo.code,
        path: crud.headerInfo.path,
        userId: crud.headerInfo.userId,
        content: JSON.stringify(crud.header)
      }
      crudHeaderProperties.add(data).then(res => {
      }).catch(err => {
      })
    },
    /**
     * 分页
     */
    toTableHead() {
      if (!callVmHook(crud, CRUD.HOOK.beforeRefresh)) {
        return
      }
      return new Promise((resolve, reject) => {
        crud.loading = true
        // 请求数据
        const data = {
          name: crud.name
        }

        initDataPlus('/api/headerProperties', data).then(res => {
          const data = res
          if (data.content && data.content.length > 0) {
            crud.header = JSON.parse(data.content[0].content).filter(item => item)
          } else {
            crud.header = []
          }
        }).catch(err => {
          reject(err)
        })
      })
    }
  })
  // 冻结处理，需要扩展数据的话，使用crud.updateProp(name, value)，以crud.props.name形式访问，这个是响应式的，可以做数据绑定
  Object.freeze(crud)
  return crud
}

// hook VM
function callVmHook(crud, hook) {
  if (crud.debug) {
  }
  let ret = true
  const nargs = [crud]
  for (let i = 2; i < arguments.length; ++i) {
    nargs.push(arguments[i])
  }
  // 有些组件扮演了多个角色，调用钩子时，需要去重
  const vmSet = new Set()
  crud.vms.forEach(vm => vm && vmSet.add(vm.vm))
  vmSet.forEach(vm => {
    if (vm[hook]) {
      ret = vm[hook].apply(vm, nargs) !== false && ret
    }
  })
  return ret
}

function mergeOptions(src, opts) {
  const optsRet = {
    ...src
  }
  for (const key in src) {
    if (opts.hasOwnProperty(key)) {
      optsRet[key] = opts[key]
    }
  }
  return optsRet
}

/**
 * crud主页
 */
function presenter(crud) {
  function obColumns(columns) {
    return {
      visible(col) {
        return !columns || !columns[col] ? true : columns[col].visible
      }
    }
  }
  return {
    inject: ['crud'],
    beforeCreate() {
      // 由于initInjections在initProvide之前执行，如果该组件自己就需要crud，需要在initInjections前准备好crud
      this._provided = {
        crud,
        'crud.query': crud.query,
        'crud.page': crud.page,
        'crud.form': crud.form
      }
    },
    data() {
      return {
        searchToggle: true,
        columns: obColumns()
      }
    },
    methods: {
      parseTime, parseData, getNowTime, dictName, parseDate, dictNameArray,
      resetColumns(columns) {
        this.columns = obColumns(columns)
        this.crud.updateProp('tableColumns', columns)
      }
    },
    created() {
      this.crud.registerVM('presenter', this, 0)
      if (crud.queryOnPresenterCreated) {
        // crud.toTableHead()
        crud.toQuery()
      }
    },
    beforeDestroy() {
      this.crud.unregisterVM(this)
    },
    mounted() {
      const columns = {}
      if (this.$refs.table) {
        this.$refs.table.columns.forEach(e => {
          if (!e.property || e.type !== 'default') {
            return
          }
          let flag = true
          if (this.crud.props.showColumns && this.crud.props.showColumns.length) {
            flag = this.crud.props.showColumns.indexOf(e.property) > -1
          }
          columns[e.property] = {
            label: e.label,
            // 在页面中配置了的字段才会显示
            visible: flag
          }
        })
        this.columns = obColumns(columns)
        this.crud.updateProp('tableColumns', columns)
      }
    }
  }
}

/**
 * 上传
 */
function upload() {
  return {
    created() {
      this.crud.registerVM('upload', this, 4)
    },
    beforeDestroy() {
      this.crud.unregisterVM(this)
    }
  }
}
/**
 * 分页2
 */
function paginations() {
  return {
    inject: {
      crud: {
        from: 'crud'
      },
      page: {
        from: 'crud.page'
      }
    },
    created() {
      this.crud.registerVM('paginations', this, 2)
    },
    beforeDestroy() {
      this.crud.unregisterVM(this)
    }
  }
}
/**
 * 头部
 */
function header() {
  return {
    inject: {
      crud: {
        from: 'crud'
      },
      query: {
        from: 'crud.query'
      }
    },
    created() {
      this.crud.registerVM('header', this, 1)
    },
    beforeDestroy() {
      this.crud.unregisterVM(this)
    }
  }
}

/**
 * 分页
 */
function pagination() {
  return {
    inject: {
      crud: {
        from: 'crud'
      },
      page: {
        from: 'crud.page'
      }
    },
    created() {
      this.crud.registerVM('pagination', this, 2)
    },
    beforeDestroy() {
      this.crud.unregisterVM(this)
    }
  }
}

/**
 * 表单
 */
function form(defaultForm) {
  return {
    inject: {
      crud: {
        from: 'crud'
      },
      form: {
        from: 'crud.form'
      }
    },
    created() {
      this.crud.registerVM('form', this, 3)
      this.crud.defaultForm = defaultForm
      this.crud.resetForm()
    },
    beforeDestroy() {
      this.crud.unregisterVM(this)
    }
  }
}

/**
 * crud
 */
function crud(options = {}) {
  const defaultOptions = {
    type: undefined
  }
  options = mergeOptions(defaultOptions, options)
  return {
    inject: {
      crud: {
        from: 'crud'
      }
    },
    created() {
      this.crud.registerVM(options.type, this)
    },
    beforeDestroy() {
      this.crud.unregisterVM(this)
    }
  }
}

/**
 * CRUD钩子
 */
CRUD.HOOK = {
  /** 刷新 - 之前 */
  beforeRefresh: 'beforeCrudRefresh',
  /** 刷新 - 之后 */
  afterRefresh: 'afterCrudRefresh',
  /** 删除 - 之前 */
  beforeDelete: 'beforeCrudDelete',
  /** 删除 - 之后 */
  afterDelete: 'afterCrudDelete',
  /** 删除取消 - 之前 */
  beforeDeleteCancel: 'beforeCrudDeleteCancel',
  /** 删除取消 - 之后 */
  afterDeleteCancel: 'afterCrudDeleteCancel',
  /** 新建 - 之前 */
  beforeToAdd: 'beforeCrudToAdd',
  /** 新建 - 之后 */
  afterToAdd: 'afterCrudToAdd',
  /** 编辑 - 之前 */
  beforeToEdit: 'beforeCrudToEdit',
  /** 编辑 - 之后 */
  afterToEdit: 'afterCrudToEdit',
  /** 开始 "新建/编辑" - 之前 */
  beforeToCU: 'beforeCrudToCU',
  /** 开始 "新建/编辑" - 之后 */
  afterToCU: 'afterCrudToCU',
  /** "新建/编辑" 验证 - 之前 */
  beforeValidateCU: 'beforeCrudValidateCU',
  /** "新建/编辑" 验证 - 之后 */
  afterValidateCU: 'afterCrudValidateCU',
  /** 添加取消 - 之前 */
  beforeAddCancel: 'beforeCrudAddCancel',
  /** 添加取消 - 之后 */
  afterAddCancel: 'afterCrudAddCancel',
  /** 编辑取消 - 之前 */
  beforeEditCancel: 'beforeCrudEditCancel',
  /** 编辑取消 - 之后 */
  afterEditCancel: 'afterCrudEditCancel',
  /** 提交 - 之前 */
  beforeSubmit: 'beforeCrudSubmitCU',
  /** 提交 - 之后 */
  afterSubmit: 'afterCrudSubmitCU',
  afterAddError: 'afterCrudAddError',
  afterEditError: 'afterCrudEditError'
}

/**
 * CRUD状态
 */
CRUD.STATUS = {
  NORMAL: 0, // 关闭弹窗
  PREPARED: 1, // 出现弹框
  PROCESSING: 2 // 处理中
}

/**
 * CRUD通知类型
 */
CRUD.NOTIFICATION_TYPE = {
  SUCCESS: 'success',
  WARNING: 'warning',
  INFO: 'info',
  ERROR: 'error'
}

export default CRUD

export {
  presenter,
  header,
  form,
  pagination,
  crud,
  upload,
  paginations
}
